from django.contrib.auth.decorators import login_required
from django.shortcuts import render,HttpResponse,redirect
from .models import Author,Blog,Record
from utils.fileutil import savefile
from django.db.models import Q
from  django.core.paginator import Paginator
from django.contrib.auth.models import User

from django.contrib.auth import login,logout,authenticate

def index(request):
    print(request.user.username)
    return render(request,'index.html')

#添加
def author_add(request):
    if request.method=='GET':
        return render(request,'author_add.html')
    if request.method=='POST':
        name=request.POST.get('name','')
        birthday=request.POST.get('birthday','')
        phone=request.POST.get('phone','')
        sex=request.POST.get('sex','')
        brief=request.POST.get('brief','')

        iconfile=request.FILES.get('icon')#这是一个文件
        icon=savefile(iconfile)


        Author.objects.create(
            name=name,
            birthday=birthday,
            phone=phone,
            sex=sex,
            brief=brief,
            icon=icon
        )
        return redirect('management:index')


def blog_add(request):
    if request.method=='GET':
        authors = Author.objects.all()
        return render(request,'blog_add.html',{'authors':authors})
    if request.method=='POST':
        title=request.POST.get('title','')
        content=request.POST.get('content','')
        publish_time=request.POST.get('publish_time','')
        update_time=request.POST.get('update_time','')
        author_id=request.POST.get('author_id','')

        Blog.objects.create(
            title=title,
            content=content,
            publish_time=publish_time,
            update_time=update_time,
            author_id=author_id,
        )
        return redirect('management:blogs')

#展示
def authors(request):
    page=request.GET.get('page','1')
    page=int(page)
    wd=request.GET.get('wd','')
    if wd:
        # authors = Author.objects.filter(name__icontains=wd).all()
        authors = Author.objects.filter(Q(name__icontains=wd) | Q(brief__icontains=wd)).all()

    else:
        authors=Author.objects.all()
    # pagesize=3
    # authors=list(authors)
    # lens1=len(authors)
    # max_y=lens1% pagesize
    # max_z=lens1//pagesize
    # if max_y !=0:
    #     max_z +=1
    # if page:
    #     authors=authors[pagesize*(page-1):pagesize*page]
    # else:
    #     pass

    pagesize=3
    paginator=Paginator(authors,pagesize)
    pagex=paginator.page(page)
    authors=pagex.object_list
    maxs=paginator.num_pages

    return render(request,'authors.html',{'authors':authors,
                                          'page':page,
                                          'pagex':pagex,
                                          'maxs':maxs,
                                          # 'max_z':max_z,
                                          })

def blogs(request):
    page=request.GET.get('page','1')
    page=int(page)
    wd=request.GET.get('wd','')
    if wd:
        blogs = Blog.objects.filter(Q(title__icontains=wd) | Q(author__name__icontains=wd)).all()

    else:
        blogs=Blog.objects.all()
    pagesize = 3
    paginator = Paginator(blogs, pagesize)
    pagex = paginator.page(page)
    blogs = pagex.object_list
    maxs = paginator.num_pages

    return render(request, 'blogs.html', {'blogs': blogs,
                                            'page': page,
                                            'pagex': pagex,
                                            'maxs': maxs,
                                            'wd': wd,
                                            # 'max_z':max_z,
                                            })


def author(request,authorid):
    author=Author.objects.get(id=authorid)
    return render(request,'author.html',{'author':author})

def blog(request,authorid):
    blog = Blog.objects.get(id=authorid)
    return render(request,'blog.html',{'blog':blog})

#修改
def author_update(request,authorid):
    author=Author.objects.get(id=authorid)
    if request.method=='GET':
        return render(request,'author_update.html',{'author':author})
    else:
        name = request.POST.get('name', '')
        birthday = request.POST.get('birthday', '')
        phone = request.POST.get('phone', '')
        sex = request.POST.get('sex', '')
        brief = request.POST.get('brief', '')

        iconfile = request.FILES.get('icon')  # 这是一个文件
        icon = savefile(iconfile)

        author.birthday=birthday
        author.phone=phone
        author.name=name
        author.sex=sex
        author.brief=brief
        author.icon=icon

        author.save()
        return redirect('management:author',authorid)


def blog_update(request,authorid):
    blog=Blog.objects.get(id=authorid)
    if request.method=='GET':
        author1=Author.objects.all()
        return render(request,'blog_update.html',{'blog':blog,'author1':author1})
    else:
        title = request.POST.get('title', '')
        content = request.POST.get('content', '')
        publish_time = request.POST.get('publish_time', '')
        update_time = request.POST.get('update_time', '')

        blog.title=title
        blog.content=content
        blog.publish_time=publish_time
        blog.update_time=update_time

        blog.save()
        return redirect('management:blog',authorid)


#删除
def author_del(request,authorid):
    author=Author.objects.get(id=authorid)
    author.delete()

    return redirect('management:authors')


def blog_del(request,authorid):
    blog=Blog.objects.get(id=authorid)
    blog.delete()
    return redirect('management:blogs')



def blogs_of_author(request,authorid):
    #反向查询：通过主表查从表
    blogs=Author.objects.get(id=authorid).blog_set.all()
    return render(request,'blogs_of_author.html',{'blogs':blogs})



#注册
def register(request):
    if request.method=='GET':
        return render(request, 'register.html')
    if request.method == 'POST':
        username=request.POST.get('username','')
        password=request.POST.get('password','')

        User.objects.create_user(username=username,password=password)
        return redirect('management:loginx')



#登录
def loginx(request):
    if request.method=='GET':
        message=''
        return render(request,'loginx.html',{'message':message})
    if request.method=='POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')

        user=authenticate(username=username,password=password)

        if user is not None:
            login(request=request,user=user)
            return redirect('management:index')
        else:
            message='没有此用户'
            return render(request,'loginx.html',{'message':message})



#登出
def logoutx(request):
    logout(request)#把session清掉
    return redirect('management:index')

@login_required
def bind_user(request):


    return render(request,'bind_user.html')



def have_author(request):
    if request.method=='GET':
        return render(request,'have_author.html')
    else:
        author=request.POST.get('author')
        try:
            author=Author.objects.get(name=author)
            try:
                r=Record.objects.get(author=author)
                return HttpResponse('已经绑定')
            except:#之前没绑定过，可以绑定
                Record.objects.create(username=request.user.username,author=author)
                return HttpResponse('绑定成功')

        except:
            return render(request,'have_author.html',{'message':'绑定失败'})





